<template>
  <div class="add-edit-content">
    <avue-crud
      :option="options"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left v-if="getTrialStatus == '1'">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleMenu(0)">新 增</el-button>
        <el-button type="primary" plain icon="el-icon-plus" @click="handleMenu(1)"
          >增加病例量</el-button
        >
<!--        <el-button type="primary" plain icon="el-icon-plus" @click="handleMenu(2)"
          >扫码控制</el-button
        >-->
        <!-- <el-button type="primary" plain icon="el-icon-plus" @click="handleMenu(3)"
          >CDISC设置</el-button
        > -->
      </template>
      <template #menu="{ row, index }">
        <el-button type="success" plain link @click="handleMenu(4, row, index)">组设计</el-button>
        <el-button type="primary" plain link @click="handleMenu(5, row)">一览表</el-button>
        <el-button
          type="warning"
          plain
          link
          @click="handleMenu(6, row)"
          v-if="getTrialStatus == '1'"
          >加容量</el-button
        >
        <el-button type="primary" plain link icon="el-icon-printer" @click="handleMenu(7, row)"
          >打印CRF</el-button
        >
      </template>
      <template #name="{ row }">
        <span style="color: #72afd2; cursor: pointer" @click="handleMenu(8, row)">{{
          row.name
        }}</span>
      </template>
      <!-- <template #deptCaseNums-label="">
        <div>机构名字</div>
      </template>
      <template #deptCaseNums-form="{type}">
        <div v-for="(item) in deptCategory" :key="item.id">{{ item.deptName }}</div>
      </template> -->
      <template #deptCaseNums-form="{}">
        <div
          v-for="item in deptCategory"
          :key="item.id"
          style="display: flex; align-items: center; margin-bottom: 5px"
        >
          <span style="width: 250px">{{ item.deptName }}</span>
          <el-input v-model="item.num" placeholder="请输入数量"></el-input>
        </div>
      </template>
    </avue-crud>
    <el-dialog v-model="isCaseload" title="增加病例量" width="500">
      <avue-form :option="caseloadOption" v-model="caseloadForm" @submit="caseloadSubmit">
        <template #TJRL="{}">
          <el-input v-model="caseloadForm.TJRL" placeholder="" type="number">
            <template #append>
              <el-button @click="handleApplyAll">应用全部</el-button>
            </template>
          </el-input>
          <div v-if="handleMenuVal.type === 1">
            增加后会即时生成随机入组顺序，为保证随机算法准确性，添加时请将各分组数量均进行增加
          </div>
        </template>
        <template #groupList="{}">
          <div
            v-for="item in caseloadForm.groupNumInfo"
            :key="item.id"
            style="display: flex; align-items: center; margin-bottom: 18px"
          >
            <span style="width: 160px; text-align: center">{{ item.name }}</span>
            <el-input
              v-model="item.num"
              placeholder="请输入数量"
              @input="handleInput(item)"
            ></el-input>
          </div>
        </template>
      </avue-form>
    </el-dialog>
    <el-dialog v-model="isPrintCrf" title="选择打印的CRF" width="500">
      <div class="print-crf">
        <el-button type="primary" plain @click="handlePrintCrf(1)">全部CRF</el-button>
        <el-button type="success" plain style="margin-left: 0" @click="handlePrintCrf(2)"
          >纳排CRF</el-button
        >
        <el-button type="warning" plain style="margin-left: 0" @click="handlePrintCrf(3)"
          >入组CRF</el-button
        >
        <el-button type="primary" plain style="margin-left: 0" @click="handlePrintCrf(4)"
          >其他定制CRF</el-button
        >
      </div>
    </el-dialog>
    <QRCodeControl ref="QRCodeControlRef" />
    <el-dialog v-model="isPrintCrfContent" title="" width="100%">
      <div id="custom-content">
        <!-- ref="`vFormRef_${item.id}`" -->
        <div v-for="(item,index) in crfListOfGroupList" :key="item.id" style="margin-bottom: 10px">
          <span style="font-size: 15px; font-weight: 550">{{ item.name }}</span>
          <VFormRender
            style="padding: 15px"
            :form-json="JSON.parse(item.content)"
            :form-data="formData"
            :option-data="optionData"
            :ref="el => setFormRef(el, index)"
          >
          </VFormRender>
        </div>
      </div>
    </el-dialog>
    <chartTable ref="chartTableRef" />
  </div>
</template>
<script setup>
import printJS from 'print-js';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  deptOfTrial,
  addGroupCaseNum,
  getCrfDetail,
  crfListOfGroup,
  crfOverviewOfGroup,
} from '@/api/group/group';
import { getTrialDetail } from '@/api/trial/trial';
import VFormRender from '@/components/form-render/index.vue';
import { groupListOfTrial } from '@/api/trial/trial';
import QRCodeControl from './groupMneu/QRCodeControl.vue';
import chartTable from './groupMneu/chartTable.vue';
import { ref, reactive, computed, onMounted, defineEmits, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import option from '@/option/group/group';
import caseloadOptions from '@/option/caseload/caseload';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const emit = defineEmits();
const options = ref(option);
const form = ref({});
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const crud = ref(null);
const store = useStore();
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const data = ref([]);
const caseloadForm = ref({});
let handleMenuVal = ref({});
let isCaseload = ref(false);
let caseloadOption = ref(caseloadOptions);
let getTrialStatus = ref('2');
let crfListOfGroupList = ref([]);
let chartTableRef = ref(null);
// permissionList 计算属性
const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
  addBtn: validData(permission.value.group_add, false),
  viewBtn: validData(permission.value.group_view, false),
  delBtn: validData(permission.value.group_delete, false),
  editBtn: validData(permission.value.group_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
let QRCodeControlRef = ref(null);
let isPrintCrf = ref(false);
/*  type:0 新增
    type:1 增加病例量
    type:2 扫码控制
    type:3 CDISC设置
    type:4 组设计
    type:5 一览表
    type:6 加容量
    type:7 打印CRF
    type:8 分组名称点击
*/
const handleMenu = (type, row = {}, index = null) => {
  for (const key in caseloadForm.value) {
    caseloadForm.value[key] = '';
  }
  handleMenuVal.value.row = row;
  handleMenuVal.value.type = type;
  handleMenuVal.value.index = index;
  const actions = {
    0: () => {
      options.value.disabled = false;
      options.value.submitBtn = true;
      options.value.emptyBtn = true;
      options.value.span = 12;
      crud.value.rowAdd();
      initData();
    },
    1: () => {
      initData();
      caseloadForm.value.groupNumInfo = [];
      groupListOfTrial(routerQuery.value.trialId).then(res => {
        const DATA = res.data.data;
        DATA.forEach(item => {
          caseloadForm.value.groupNumInfo.push({
            groupId: item.id,
            num: 0,
            name: item.name,
          });
        });
      });
      isCaseload.value = true;
    },
    2: () => {
      nextTick(() => {
        QRCodeControlRef.value.openSetting();
      });
    },
    4: () => {
      // crud.value.rowDel(row, index);
      router.push({
        path: '/trial/groupTab',
        query: {
          selectTab: 2,
          trialId: routerQuery.value.trialId,
          groupId: row.id,
        },
      });
    },
    5: () => {
      nextTick(() => {
        chartTableRef.value.open(row);
      });
    },
    6: () => {
      initData();
      caseloadForm.value.groupNumInfo = [];
      groupListOfTrial(routerQuery.value.trialId).then(res => {
        const DATA = res.data.data;
        DATA.forEach(item => {
          caseloadForm.value.groupNumInfo.push({
            groupId: item.id,
            num: 0,
            name: item.name,
          });
        });
      });
      isCaseload.value = true;
    },
    7: () => {
      isPrintCrf.value = true;
    },
    8: () => {
      // emit('groupChange', row);
      router.push({
        path: '/trial/groupTab',
        query: {
          selectTab: 2,
          trialId: routerQuery.value.trialId,
          groupId: row.id,
        },
      });
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};

let isPrintCrfContent = ref(false);
const vFormRefs = ref([]); // 保存所有子组件实例的数组
const formJson = ref({});
// const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});
// 动态绑定 ref 到数组
const setFormRef = (el, index) => {
  if (el) {
    vFormRefs.value[index] = el;
  }
};
// 打印CRF弹窗里按钮点击事件
/*
  type 1：全部CRF
  type 2：纳排CRF
  type 3：入组CRF
  type 4：其他定制CRF
*/
const handlePrintCrf = type => {
  isPrintCrfContent.value = true;
  getDetailData(type, handleMenuVal.value.row.id);
};
const getDetailData = async (type, groupId) => {
  const { data: res } = await crfListOfGroup(type, groupId);
  if (res.code == 200) {
    crfListOfGroupList.value = res.data;
    nextTick(() => {
      // 遍历所有子组件实例并调用方法
      crfListOfGroupList.value.forEach((item, index) => {
        const formJson = JSON.parse(item.content);
        if (vFormRefs.value[index]) {
          vFormRefs.value[index].setFormJson(formJson);
        }
      });
      setTimeout(() => {
        printJS({
          printable: 'custom-content', // 容器 ID
          type: 'html', // 指定打印类型为 HTML
          //   style: `                      // 自定义打印样式（可选）
          //   @page { size: A4; margin: 10mm; }
          //   h2 { color: #333; }
          //   .content-box { border: 1px solid #ddd; padding: 10px; }
          // `,
          style: `
            @media print {
              .el-input__prefix,
              .el-input__suffix {
                display: none !important;
              }
            }
          `,
          scanStyles: false, // 是否扫描页面样式（true 时会继承页面原有样式）
          targetStyles: ['*'], // 指定继承哪些页面样式（['*'] 表示全部）
          // ignoreElements: ['button'], // 隐藏容器内不需要打印的元素（可选）
        });
        setTimeout(() => {
          isPrintCrfContent.value = false;
        }, 100);
      }, 500);
    });
  }
};

let deptCategory = ref([]);
import { findObject } from '@smallwei/avue';
const initData = () => {
  form.value.deptCaseNums = [];
  deptOfTrial(routerQuery.value.trialId).then(res => {
    deptCategory.value = [];
    let DATA = res.data.data;
    res.data.data.forEach(item => {
      deptCategory.value.push({
        deptName: item.deptName,
        deptId: item.id,
        num: 0,
      });
    });
    const column = findObject(caseloadOption.value.column, 'dept');
    console.log(column);
    column.dicData = DATA;
    // caseloadForm.value.hospitalDeptName = DATA.map(ele => ele.deptName).join(',');
    // caseloadForm.value.dept = DATA.map(ele => ele.id).join(',');
    console.log(form.value.deptCaseNums);
  });
};
// 增加病例量提交按钮
const caseloadSubmit = (form, done) => {
  let val = JSON.parse(JSON.stringify(form));
  delete val.hospitalDeptName;
  val.trialId = routerQuery.value.trialId;
  val.groupNumInfo = JSON.stringify(val.groupNumInfo);
  addGroupCaseNum(val).then(
    res => {
      ElMessage.success('操作成功!');
      onLoad(page.value);
      isCaseload.value = false;
      done();
    },
    error => {
      done();
    }
  );
  done();
};
const handleInput = item => {
  // let sum = sumValues(caseloadForm.value.groupNumInfo);
  // caseloadForm.value.TJRL = sum;
  caseloadForm.value.SZTJ = sumValues(caseloadForm.value.groupNumInfo);
  console.log(item, caseloadForm.value.groupNumInfo);
};
// 增加病例量-应用全部按钮点击
const handleApplyAll = () => {
  caseloadForm.value.groupNumInfo.forEach(item => {
    item.num = Number(caseloadForm.value.TJRL);
  });
  // caseloadForm.value.YJZ = caseloadForm.value.CSZ = Number(caseloadForm.value.TJRL);
  caseloadForm.value.SZTJ = sumValues(caseloadForm.value.groupNumInfo);
};
onMounted(() => {
  options.value.column.forEach(item => {
    if (item.prop === 'deptCaseNums') {
      item.display = true;
    }
    if (item.prop === 'caseNum') {
      item.disabled = false;
    }
    if (item.prop === 'collectionSequence') {
      item.disabled = false;
    }
  });
  getTrialStatus.value = '2';
  initTrialDetail(routerQuery.value.trialId);
});
const initTrialDetail = id => {
  if (id) {
    getTrialDetail(id).then(res => {
      getTrialStatus.value = res.data.data.status;
    });
  }
};
// 数组求和
const sumValues = array => {
  return array.reduce((sum, item) => {
    return sum + Number(item.num); // 将 value 转换为数字后累加
  }, 0); // 初始值为 0
};
const rowSave = (row, done, loading) => {
  // row.deptCaseNums = [{deptId:1907350352384905218,num:852},{deptId:1907354183659311106,num:1000}]
  console.log(row);
  let scalSum = sumValues(deptCategory.value);
  if (Number(scalSum) != Number(row.caseNum)) {
    ElMessage.warning('部门病例数量总和与病例数量不相等，请检查！');
    loading();
    return;
  }
  row.deptCaseNums = JSON.stringify(deptCategory.value);
  row.trial = routerQuery.value.trialId;
  add(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  update(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const beforeOpen = (done, type) => {
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};

const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};

const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    trial: routerQuery.value.trialId,
    ...params,
  };
  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    loading.value = false;
    selectionClear();
  });
};
</script>
<style scoped>
.add-edit-content {
  width: 90%;
  height: 100%;
}
.print-crf {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
@media print {
  .el-input__prefix,
  .el-input__suffix {
    display: none !important;
  }
}
</style>
